import request from "@/utils/request";

// 获取 BentoML 部署服务状态列表
export function getDeploymentStatus() {
  return request({
    url: "/deploy/bentoml/service-status/options",
    method: "get",
  });
}

// 获取 BentoML 部署服务列表（Bento 包列表）
export function listDeploymentServices(params = {}) {
  return request({
    url: "/deploy/bentoml/packages",
    method: "get",
    params: {
      // 这里将前端的查询条件映射到后端的查询参数
      bento_name: params.service_name || undefined,
      service_name: params.service_name || undefined,
      host: params.service_host || undefined,
      status: params.service_status || undefined,
    },
  });
}

// （兼容旧调用）搜索服务列表：直接复用 listDeploymentServices
export function searchDeploymentServices(query) {
  return listDeploymentServices(query);
}

// 获取指定 Bento 包（部署服务）详情
export function getDeploymentService(serviceId) {
  return request({
    url: "/deploy/bentoml/package/" + serviceId,
    method: "get",
  });
}

// 构建 Bento 包（新建部署）
export function buildBentoPackage(data) {
  return request({
    url: "/deploy/bentoml/package/build",
    method: "post",
    data: data,
  });
}

// 创建服务配置（保留旧接口，BentoML 新建由 /deploy/bentoml/package/build 负责）
export function createDeploymentService(data) {
  return request({
    url: "/deploy/add",
    method: "post",
    data: data,
  });
}

// 更新指定 Bento 包（服务配置），对应 BentoUpdateRequest
export function updateDeploymentService(serviceId, data) {
  // 如果传入的数据已经是完整的 BentoUpdateRequest 结构，直接使用
  // 否则进行映射（兼容旧调用方式）
  let requestBody;
  if (data.service_info && data.api_info) {
    // 已经是完整的 BentoUpdateRequest 结构
    requestBody = data;
  } else {
    // 兼容旧的数据结构，进行映射
    const serviceInfo = {
      service_name: data.service_name,
      service_code: data.service_code,
      report_code: data.report_code || data.service_code || "",
      task_id: data.task_id,
      service_host: data.service_host || null,
      api_method: data.api_method,
      api_path: data.api_path,
      api_request_class: data.api_request_class,
      api_response_class: data.api_response_class,
      description: data.description,
    };

    const apiInfo = {
      api_method: data.api_method || null,
      api_host: data.api_host || null,
      api_path: data.api_path || null,
      api_headers: { "Content-Type": "application/json" },
      api_params: { dataset: "test_data" },
      request_class: data.api_request_class || null,
      response_class: data.api_response_class || null,
    };

    requestBody = {
      service_info: serviceInfo,
      api_info: apiInfo,
      replace_existing: true,
    };
  }

  return request({
    url: "/deploy/bentoml/package/" + serviceId,
    method: "put",
    data: requestBody,
  });
}

// 删除指定 Bento 包（服务）
export function delDeploymentService(serviceId) {
  return request({
    url: "/deploy/bentoml/package/" + serviceId,
    method: "delete",
  });
}

// 批量删除 Bento 包（服务）——后端无批量接口，这里循环调用
export function delDeploymentServiceBatch(serviceIds) {
  return Promise.all(
    serviceIds.map((id) =>
      request({
        url: "/deploy/bentoml/package/" + id,
        method: "delete",
      })
    )
  );
}

// 启动 Bento 包对应的 Docker 服务
export function startDeploymentService(serviceId, data = {}) {
  // 如果传入的数据为空，使用默认值
  const requestData = {
    service_name: data.service_name || null,
    host: data.host || "0.0.0.0",
    port: data.port || 3000,
    target_port: data.target_port || 3000,
    image_tag: data.image_tag || null,
    container_name: data.container_name || null,
    env_vars: data.env_vars || null,
    platform: data.platform || null,
    build_args: data.build_args || null,
    api_info: data.api_info || null,
  };

  return request({
    url: "/deploy/bentoml/package/" + serviceId + "/docker/run",
    method: "post",
    data: requestData,
  });
}

// 停止 Bento 包对应的 Docker 服务
export function stopDeploymentService(serviceId) {
  return request({
    url: "/deploy/bentoml/package/" + serviceId + "/docker/stop",
    method: "post",
  });
}

// 获取训练任务列表（BentoML 训练任务）
export function getTrainingTaskList(params = {}) {
  return request({
    url: "/training/bentoml/tasks",
    method: "get",
    params: {
      status: params.status || undefined,
      limit: params.limit || 100,
    },
  });
}

// 获取资源列表
export function getResourceList() {
  return request({
    url: "/resources/list",
    method: "get",
  });
}

// 获取资源类型列表
export function getResourceTypes() {
  return request({
    url: "/resources/list_types",
    method: "get",
  });
}

// 获取扩容类型列表
export function getCapacityModes() {
  return request({
    url: "/resources/list_capacity_modes",
    method: "get",
  });
}

// 上传requirements文件
export function uploadRequirementsFile(file) {
  const formData = new FormData();
  formData.append("file", file);
  return request({
    url: "/resources/upload",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

// 上传数据API配置文件
export function uploadDataApiSpecs(file) {
  const formData = new FormData();
  formData.append("file", file);
  return request({
    url: "/data_api/upload",
    method: "post",
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}
